<template>
  <div id="space-detail-page">
    <!--空间信息-->
    <a-flex justify="space-between">
      <h2>{{ space.spaceName }}({{ SPACE_TYPE_MAP[space.spaceType ?? 0] }})</h2>
      <a-space class="middle">
        <a-button v-if="canUploadPicture" type="primary" :href="`/add-picture?spaceId=${space.id}`">+ 创建图片</a-button>
        <a-button v-if="canManageSpaceUser" type="primary" ghost :href="`/space-user-manager/${id}`">成员管理</a-button>
        <a-button
          v-if="canViewPicture"
          type="primary"
          :icon="h(BarChartOutlined)"
          :href="`/space-analyze?spaceId=${space.id}`"
          >空间分析
        </a-button>
        <a-button v-if="canEditPicture" type="primary" ghost :icon="h(EditOutlined)" @click="doBatchEdit"
          >批量编辑
        </a-button>
        <a-tooltip
          :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`"
        >
          <a-progress
            type="circle"
            :percent="(((space.totalSize ?? 0) * 100) / (space.maxSize ?? 1)).toFixed(1)"
            :size="42"
          />
        </a-tooltip>
      </a-space>
    </a-flex>
    <!--搜索表单 -->
    <picture-search-form :on-search="onSearch" />
    <!--按照颜色搜索-->
    <a-form-item v-if="canViewPicture" label="按照颜色搜索" style="margin-top: 16px">
      <color-picker format="hex" @pureColorChange="onColorChange" />
    </a-form-item>
    <div style="margin-bottom: 16px"></div>
    <!--图片列表-->
    <picture-list :dataList="dataList" :loading="loading" :show-ops="true" :can-delete="canDeletePicture" :can-edit="canEditPicture" />
    <!-- 分页器 -->
    <a-pagination
      style="text-align: right"
      v-model:current="searchParams.pageNum"
      v-model:pageSize="searchParams.pageSize"
      :total="total"
      :show-total="() => `图片总数${total}/${space.maxCount}`"
      @change="onPageChange"
    />
    <batch-edit-picture-modal
      ref="batchEditPictureModalRef"
      :picture-list="dataList"
      :space-id="id as number"
      :on-success="onBatchEditPictureSuccess"
    />
  </div>
</template>
<script setup lang="ts">
import PictureList from '@/components/PictureList.vue'
import { computed, h, onMounted, ref, watch } from 'vue'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/request/api/pictureController.ts'
import { message } from 'ant-design-vue'
import { getSpaceVoByIdUsingGet } from '@/request/api/spaceController.ts'
import { formatSize } from '@/utils'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { ColorPicker } from 'vue3-colorpicker'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { BarChartOutlined, EditOutlined } from '@ant-design/icons-vue'
import { SPACE_PERMISSION_ENUM, SPACE_TYPE_MAP } from '@/constants/spaceUserConstant.ts'

const props = defineProps<{
  id: number | string
}>()
const searchParams = ref<API.PictureQueryRequest>({
  pageNum: 1,
  pageSize: 12,
  sortFields: ['createTime'],
  sortOrders: [0],
})
const dataList = ref<API.PictureVO[]>([])
const total = ref(0)
const loading = ref(false)
const space = ref<API.SpaceVO>({})

// 获取空间信息
const fetchSpaceDetail = async () => {
  try {
    const { data: res } = await getSpaceVoByIdUsingGet({
      id: props.id as number,
    })
    if (res.code == 0 && res.data) {
      space.value = res.data
    } else {
      message.error('获取空间信息失败,' + res.message)
    }
  } catch (e: any) {
    message.error('获取空间信息失败,' + e.message)
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  const params: API.PictureQueryRequest = {
    ...searchParams.value,
    spaceId: props.id as number,
  }
  const { data: res } = await listPictureVoByPageUsingPost(params)
  if (res.data) {
    dataList.value = res.data.records ?? []
    total.value = res.data.total ?? 0
  } else {
    message.error('获取数据失败,' + res.message)
  }
  loading.value = false
}
const onPageChange = (page: number, pageSize: number) => {
  searchParams.value.pageNum = page
  searchParams.value.pageSize = pageSize
  fetchData()
}
const onSearch = (newSearchParams: API.PictureQueryRequest) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    pageNum: 1,
  }
  fetchData()
}
// 颜色搜索
const onColorChange = async (color: string) => {
  const { data: res } = await searchPictureByColorUsingPost({
    picColor: color,
    spaceId: props.id as number,
  })
  if (res.code == 0 && res.data) {
    dataList.value = res.data ?? []
    total.value = res.data.length
  } else {
    message.error('获取数据失败,' + res.message)
  }
}
// 获取批量修改图片模态框
const batchEditPictureModalRef = ref<InstanceType<typeof BatchEditPictureModal>>()
const onBatchEditPictureSuccess = () => {
  // 重新获取数据
  fetchData()
}
const doBatchEdit = () => {
  // 弹框
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}
watch(
  () => props.id,
  () => {
    // 空间id发生改变时，触发
    fetchData()
    fetchSpaceDetail()
  },
)
// 根据permission动态创建权限校验器
const createPermissionChecker = (permission: string) => {
  return computed(() => (space.value.permissions ?? []).includes(permission))
}
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canViewPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_VIEW)


onMounted(() => {
  fetchSpaceDetail()
  fetchData()
})
// 获取空间详情
</script>

<style scoped lang="less"></style>
